/**
 * Script for the search video page
 */
var PageSearchWords = new (function() {
	var $this = this;
	var videosDisplayed = [];
	var loadingFirst = false;
	var loadingNext = false;
	var haveMore = true;
	var haveError = false;
	var ajax;
	
	/**
	 * Initialization
	 * Load the last status saved
	 */
	this.init = function(e, data) {
		loadVideoSearch();
		if (!videosDisplayed.length && !$("#search-words-offset").val() && $("#words-search").val()) {
			$this.searchVideos($("#words-search").val());
		}
	}
	
	
	/**
	 * Search a video with keywords
	 */
	this.searchVideos = function(keywords) {
		var dataAjax = {
			keywords: keywords, 
			login: MikuClip.options.login, 
			password: MikuClip.options.password,
			sort: $("#search-words-sort").val()
		};
		if ($("#search-words-offset").val()) {
			dataAjax.offset = $("#search-words-offset").val();
		}
		
		if (ajax) {
			ajax.abort();
			ajax = null;
		}		
		
		if (!dataAjax.offset) {
			loadingFirst = true;
			clearListView();
		}
		else {
			loadingNext = true;
		}
		haveMore = true;
		haveError = false;
		updateListView();
		
		ajax = $.ajax({
			url: MikuClip.URL.WEBSERVICE_VIDEOS_SEARCH,
			data: dataAjax,
			type: 'POST',
			success: function(data) {
				try {
					
					var videos = JSON.parse(data);
					saveVideoSearch();
					if (videos.error_type && videos.error_type == "connection") {
						DialogConnectMikubook.setError(videos.error);
						DialogConnectMikubook.show();
					}
					else {
						for (var i = 0; i < videos.length; i++) {
							addToListView(videos[i]);
							videosDisplayed.push(videos[i]);
						}
						loadingNext = false;
						loadingFirst = false;
						if (videos.length == 0) {
							haveMore = false;
						}
						
						updateListView();
						$("#search-words-offset").val($("#page-search-words #listview .video-item").length);
						
						saveVideoSearch();
						ajax = null;
					}
				}
				catch (e) {
					onError({statusText: 'parsing_error'});
				}
			},
			error: onError
		});
	}
	
	/**
	 * Error occured (403, 404, ...) or parsing error
	 */
	function onError(e) {
		loadingNext = false;
		loadingFirst = false;
		if (e.statusText != "abort") {
			haveError = true;
		}
		ajax = null;
		updateListView();
	}
	
	/**
	 * When a search is validated
	 */
	function onSearch() {
		var input = $(this);
		clearListView();
		
		videosDisplayed = [];
		haveError = false;
		
		updateListView();
		saveVideoSearch();
		
		if (ajax) {
			ajax.abort();
			ajax = null;
		}
		
		$("#search-words-offset").val('');
		if (input.val() != "") {
			$this.searchVideos(input.val());
		}
	}
	
	/**
	 * Click on "More elements"
	 */
	function onMoreVideo() {
		var input = $("#words-search");
		$this.searchVideos(input.val());
	}
	
	/**
	 * Click on the refresh button
	 */ 
	function onRefresh() {
		$("#search-words-offset").val('');
		videosDisplayed = [];
		var input = $("#words-search");
		$this.searchVideos(input.val());		
	}
	
	/**
	 * Click on a tab for sorting resukts
	 */
	function onSort() {
		var link = $(this);
		var input = $("#words-search");
		clearListView();
		videosDisplayed = [];
		haveError = false;
		
		updateListView();
		saveVideoSearch();
		
		if (ajax) {
			ajax.abort();
			ajax = null;
		}
		
		$("#search-words-offset").val('');
		$("#search-words-sort").val(link.attr("sort-data"));
		if (input.val() != "") {
			$this.searchVideos(input.val());
		}		
	}	
		
	/**
	 * Save the current status of the page (video loading, videos displayed, offset)
	 */
	function saveVideoSearch() {
		window.localStorage['page_searchWords'] = JSON.stringify({
			'keywords': $("#words-search").val(),
			'offset': $("#search-words-offset").val(),
			'videos': videosDisplayed,
			'loadingNext': loadingNext,
			'loadingFirst': loadingFirst,
			'haveMore': haveMore,
			'sort': $("#search-words-sort").val()
		});
	}
	
	/**
	 * Load the saved status of the page
	 */
	function loadVideoSearch() {
		if (window.localStorage['page_searchWords']) {
			var o = JSON.parse(window.localStorage['page_searchWords']);
			$("#words-search").val(o.keywords);
			$("#search-words-offset").val(o.offset);
			$("#search-words-sort").val(o.sort);
			
			$("#page-search-words .btn-listview-sort").removeClass("ui-btn-active");
			$("#page-search-words .btn-listview-sort[sort-data='"+o.sort+"']").addClass("ui-btn-active");
			videosDisplayed = [];
			
			if (!o.loadingFirst) {
				clearListView();
				for (var i = 0; i < o.videos.length; i++) {
					addToListView(o.videos[i]);
					videosDisplayed.push(o.videos[i]);
				}
			}
			
			updateListView();
			
			if ($("#words-search").val() && (o.loadingNext || o.loadingFirst)) {
				$this.searchVideos($("#words-search").val());
			}
			
		}
	}
	
	/**
	 * Update the main listview (more element, loading, error, no videos)
	 */
	function updateListView() {
		if (loadingFirst) {
			$("#page-search-words #listview-loader-top").css("display", "block");
		}
		else {
			$("#page-search-words #listview-loader-top").css("display", "none");
		}
		
		if (loadingNext) {
			$("#page-search-words #listview-loader-bottom").css("display", "block");
		}
		else {
			$("#page-search-words #listview-loader-bottom").css("display", "none");
		}
		
		if (videosDisplayed.length && haveMore && !loadingFirst && !loadingNext) {
			$("#page-search-words #listview-item-more").css("display", "block");
		}
		else {
			$("#page-search-words #listview-item-more").css("display", "none");
		}
	
	
		if (!haveError && $("#words-search").val() && !videosDisplayed.length && !loadingFirst && !loadingNext) {
			$("#page-search-words #listview-item-notfound").css("display", "block");
		}
		else {
			$("#page-search-words #listview-item-notfound").css("display", "none");
		}
		
		if (haveError) {
			$("#page-search-words #listview-item-error").css("display", "block");
		}
		else {
			$("#page-search-words #listview-item-error").css("display", "none");
		}
		
		refreshListView();
	}
	
	/**
	 * Clear the main list view
	 */
	function clearListView() {
		$("#page-search-words #listview .video-item").remove();
		refreshListView();
	}
	
	/**
	 * Add an video to listview
	 */
	function addToListView(videodata) {
		var video = new VideoItem(videodata);
		$("#page-search-words #listview-loader-bottom").before(video.dom);
		refreshListView();
	}
	
	/**
	 * Refresh the JQuery Mobile Widget, if loaded
	 */
	function refreshListView() {
		try {
			$("#page-search-words #listview").listview('refresh');
		} catch(e) {
		}
	}	

	
	$("body").on("pagebeforeshow", "#page-search-words", this.init);
	$("#page-search-words #listview-item-more").on("click", onMoreVideo);
	$("#page-search-words").on("change", "#words-search", onSearch);
	$("#page-search-words").on("click", "#btn-refresh", onRefresh);
	$("#page-search-words").on("click", ".btn-listview-sort", onSort);
});